package auth_svc

import (
	"admin-system/internal/dao"
	"admin-system/internal/models/auth_model"
	"admin-system/internal/request"
	"errors"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

type AdminService struct {
	dao *dao.DaoProvider
}

func NewAdminService(dao *dao.DaoProvider) *AdminService {
	return &AdminService{
		dao: dao,
	}
}

// Login 登录
// @param ctx 接口传入参数
func (a *AdminService) Login(ctx *gin.Context, req request.LoginRequest) (*auth_model.Admin, error) {
	//查询用户信息
	admin, err := a.dao.AdminDao.GetByUsername(ctx, req.Username)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("用户不存在")
		}
		return nil, err
	}

	// 验证密码
	if err = bcrypt.CompareHashAndPassword([]byte(admin.Password), []byte(req.Password)); err != nil {
		return nil, errors.New("密码错误")
	}
	// 查询用户的 角色
	adminInfo, err := a.dao.AdminDao.GetUserInfoByID(ctx, admin.ID)
	if err != nil {
		return nil, err
	}
	// 传递上下文
	ctx.Set("admin", adminInfo)
	return admin, nil
}

// CreateAdminUser
// @param ctx 接口传入参数
func (a *AdminService) CreateAdminUser(ctx *gin.Context, req request.CreateAdminUserRequest) (*auth_model.Admin, error) {
	// 创建用户
	admin := &auth_model.Admin{
		Avatar:   req.Avatar,
		Email:    req.Email,
		Mobile:   req.Mobile,
		Nickname: req.Nickname,
		Password: req.Password,
		RoleID:   req.RoleID,
		Status:   req.Status,
		Username: req.Username,
	}
	if err := a.dao.AdminDao.CreateAdminUser(ctx, admin); err != nil {
		return nil, err
	}
	return admin, nil
}

// GetUserInfoByID
// @param ctx 接口传入参数
// @param userId 用户ID
//
//	@return *auth_model.Admin
func (a *AdminService) GetUserInfoByID(ctx *gin.Context, userId int64) (*auth_model.Admin, error) {
	return a.dao.AdminDao.GetUserInfoByID(ctx, userId)
}
